package com.ngrok.client;

import com.ngrok.NgrokApi;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.net.InetSocketAddress;

/**
 * Created by pj on 2017/9/27.
 */
public abstract class NettyClient {
    private final static Logger loger= LoggerFactory.getLogger(NettyClient.class);

    private Bootstrap bootstrap;
    private EventLoopGroup group;

    public NettyClient(EventLoopGroup group){
        this.group=group;
    }

    public void open(ChannelInitializer channelInitializer){
            bootstrap=new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(channelInitializer)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,1000);
//                    .option(ChannelOption.SO_TIMEOUT, 5000);

    }

    public Channel connect(String host,int prot) {
        Assert.notNull(bootstrap,"Bootstrap is Null");
//        Assert.notNull(host,"Host or ip is Null");
        ChannelFuture channelFuture=null;
        try{
            channelFuture =bootstrap.connect(new InetSocketAddress(host,prot)).sync();
            channelFuture.addListener(future->{
                if (future.isSuccess()) {
                    System.out.println("链接成功");
                }else {
                    System.out.println("链接失败");
                }
            });
            if(channelFuture.isSuccess()){
                return channelFuture.channel();
            }
            return null;
        }catch (Exception e){
//            e.printStackTrace();
            loger.error(e.getMessage());
        }
        return null;
    }

    public EventLoopGroup getGroup() {
        return group;
    }

    public Bootstrap getBootstrap() {
        return bootstrap;
    }
}
